package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.TravelContent;
import cn.wolfcode.trip.base.mapper.TravelContentMapper;
import cn.wolfcode.trip.base.mapper.TravelMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService{
    @Autowired
    private TravelMapper travelMapper;
    @Autowired
    private TravelContentMapper contentMapper;


    @Override
    public void saveOrUpdate(Travel travel) {
        Date date = new Date();
        TravelContent travelContent = travel.getTravelContent();
        if (travel.getId() == null) {
            travel.setAuthor(UserContext.getCurrentUser());
            travel.setCreateTime(date);
            travel.setLastUpdateTime(date);
            travelMapper.insert(travel);
            //由于只有先保存好游记的id,在保存TravelContent对象
            //保存游记对象
            //设置关联id
            travelContent.setId(travel.getId());
            contentMapper.insert(travelContent);
        }else{
            travel.setLastUpdateTime(date);
            travelMapper.updateByPrimaryKey(travel);
            //设置关联id
            travelContent.setId(travel.getId());
            contentMapper.updateByPrimaryKey(travelContent);

        }
    }

    @Override
    public PageInfo list(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(),qo.getOrderBy());
        List<Travel> list = travelMapper.selectForList(qo);
        return new PageInfo<>(list);
        
    }

    @Override
    public Travel selectById(Long id) {
        return travelMapper.selectByPrimaryKey(id);
    }

    @Override
    public void updateStateById(Travel travel) {
        if (travel.getState()== Travel.STATE_RELEASE) {
            travel.setReleaseTime(new Date());
        }
        travelMapper.updateStateById(travel);
    }

    @Override
    public TravelContent getContentById(Long id) {
        return contentMapper.selectByPriamryKey(id);
    }


}
